{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Next Closest Time"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Medium"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #string #enumeration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #字符串 #枚举"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: nextClosestTime"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #最近时刻"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>给定一个形如<meta charset=\"UTF-8\" />&nbsp;<code>\"HH:MM\"</code> 表示的时刻<meta charset=\"UTF-8\" />&nbsp;<code>time</code>&nbsp;，利用当前出现过的数字构造下一个距离当前时间最近的时刻。每个出现数字都可以被无限次使用。</p>\n",
    "\n",
    "<p>你可以认为给定的字符串一定是合法的。例如，<meta charset=\"UTF-8\" />&nbsp;<code>\"01:34\"</code> 和 <meta charset=\"UTF-8\" />&nbsp;<code>\"12:09\"</code> 是合法的，<code>“1:34”</code> 和 <code>“12:9”</code> 是不合法的。</p>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>示例 1:</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入:</strong> \"19:34\"\n",
    "<strong>输出:</strong> \"19:39\"\n",
    "<strong>解释:</strong> 利用数字 <strong>1, 9, 3, 4</strong> 构造出来的最近时刻是 <strong>19:39</strong>，是 5 分钟之后。\n",
    "结果不是 <strong>19:33</strong> 因为这个时刻是 23 小时 59 分钟之后。\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 2:</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入:</strong> \"23:59\"\n",
    "<strong>输出:</strong> \"22:22\"\n",
    "<strong>解释:</strong> 利用数字 <strong>2, 3, 5, 9</strong> 构造出来的最近时刻是 <strong>22:22</strong>。 \n",
    "答案一定是第二天的某一时刻，所以选择可构造的最小时刻。\n",
    "</pre>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>提示：</strong></p>\n",
    "\n",
    "<p><meta charset=\"UTF-8\" /></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>time.length == 5</code></li>\n",
    "\t<li><code>time</code>&nbsp;为有效时间，格式为&nbsp;<code>\"HH:MM\"</code>.</li>\n",
    "\t<li><code>0 &lt;= HH &lt; 24</code></li>\n",
    "\t<li><code>0 &lt;= MM &lt; 60</code></li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [next-closest-time](https://leetcode.cn/problems/next-closest-time/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [next-closest-time](https://leetcode.cn/problems/next-closest-time/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['\"19:34\"', '\"23:59\"']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        allowed_digits = set(time) - set(\":\")\n",
    "\n",
    "        hours, minutes = map(int, time.split(\":\"))\n",
    "        total_minutes = hours * 60 +  minutes\n",
    "\n",
    "        def is_valid(time):\n",
    "            return all(digit in allowed_digits for digit in \"{:02d}{:02d}\".format(*divmod(time, 60)))\n",
    "        \n",
    "        for i in range(total_minutes + 1, total_minutes + 1441):\n",
    "            if is_valid(i % 1440):\n",
    "                return \"{:02d}:{:02d}\".format(*divmod(i % 1440, 60))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        cand = set()\n",
    "        for t1 in time:\n",
    "            for t2 in time:\n",
    "                if t1 != \":\" and t2 != \":\":\n",
    "                    tt = t1+t2\n",
    "                    cand.add(tt)\n",
    "        double_digits = list(cand)\n",
    "        double_digits.sort()\n",
    "        time = list(time.split(\":\"))\n",
    "        hour, minute = time[0], time[1]\n",
    "        \n",
    "        idx = double_digits.index(minute)\n",
    "        if idx == len(double_digits)-1:\n",
    "            minute = double_digits[0]\n",
    "        else:\n",
    "            if int(double_digits[idx+1]) < 60:\n",
    "                minute = double_digits[idx+1]\n",
    "                return hour + \":\" + minute\n",
    "            else:\n",
    "                minute = double_digits[0]\n",
    "\n",
    "        idx = double_digits.index(hour)\n",
    "        if idx == len(double_digits)-1:\n",
    "            hour = double_digits[0]\n",
    "        else:\n",
    "            if int(double_digits[idx+1]) < 24:\n",
    "                hour = double_digits[idx+1]\n",
    "            else:\n",
    "                hour = double_digits[0]\n",
    "    \n",
    "        return hour + \":\" + minute\n",
    "\n",
    "\n",
    "            \n",
    "            \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        h = int(time[:2])\n",
    "        m = int(time[-2:])\n",
    "        t = h * 60 + m\n",
    "\n",
    "        cand = list({h%10,h//10,m%10,m//10})\n",
    "\n",
    "        ans = 1440\n",
    "        for i,j,k,l in itertools.product(cand,repeat=4):\n",
    "            if (h:=10*i+j)<24 and (m:=10*k+l)<60:\n",
    "                if (nt := h * 60 + m) != t:\n",
    "                    dt = (nt - t) % 1440\n",
    "                    ans = min(ans, dt)\n",
    "        \n",
    "        nt = t + ans\n",
    "        m = nt % 60\n",
    "        h = (nt // 60) % 24\n",
    "        return f\"{h:02}:{m:02}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        # if time[0]: return '00:00' # handle special case\n",
    "\n",
    "        nums = list(map(int, [time[0], time[1], time[3], time[4]]))\n",
    "        h = int(time[:2]) # input HH\n",
    "        m = int(time[3:]) # input MM\n",
    "\n",
    "        h_candidates = set()\n",
    "        m_candidates = set()\n",
    "        for n1 in set(nums):\n",
    "            for n2 in set(nums):\n",
    "                num = int(n1* 10 + n2)\n",
    "                if 0 <= num < 24:\n",
    "                    h_candidates.add(num)\n",
    "                if 0 <= int(num) < 59:\n",
    "                    m_candidates.add(num)\n",
    "                \n",
    "        h_candidates = list(h_candidates)\n",
    "        h_candidates = sorted(h_candidates, key=lambda x: x if x >= h else x + 24)\n",
    "        m_candidates = sorted(list(m_candidates))\n",
    "        print(h_candidates)\n",
    "        print(m_candidates)\n",
    "        for h_cand in h_candidates:\n",
    "            for m_cand in m_candidates:\n",
    "                print(f'{h_cand:02}:{m_cand:02}')\n",
    "                if h_cand != h:\n",
    "                    return f'{h_cand:02}:{m_cand:02}'\n",
    "                elif h_cand == h and m_cand > m:\n",
    "                    return f'{h_cand:02}:{m_cand:02}'\n",
    "        return time\n",
    "                    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def __init__(self):\n",
    "        self.time = float('inf')\n",
    "        self.cur_str = []\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        # 获取合法数字\n",
    "        number = list(set(list(time.strip())))\n",
    "        number.remove(':')\n",
    "        number.sort()\n",
    "        if len(number) == 1: return time\n",
    "        # 进行遍历\n",
    "        cur_time = list(map(lambda x: int(x), time.strip().split(':')))\n",
    "        point = cur_time[0] * 60 + cur_time[1]\n",
    "        def search_time(time):\n",
    "            if len(time) == 4:\n",
    "                if int(''.join(time[-2:])) < 59:\n",
    "                    cur_point = int(''.join(time[:2])) * 60 + int(''.join(time[2:]))\n",
    "                    if cur_point < point:\n",
    "                        cur_point += 1440 \n",
    "                    elif cur_point == point:\n",
    "                        return None\n",
    "                    if self.time > cur_point - point:\n",
    "                        self.time = cur_point-point\n",
    "                        print(self.time)\n",
    "                        print(time)\n",
    "                        self.cur_str = time[:]\n",
    "                \n",
    "                return None\n",
    "            elif len(time) == 2:\n",
    "                if int(''.join(time)) > 23:\n",
    "                    return None\n",
    "            for i in number:\n",
    "                time.append(i)\n",
    "                search_time(time)\n",
    "                time.pop()\n",
    "        \n",
    "        search_time([])\n",
    "        print(self.cur_str)\n",
    "        return ':'.join([''.join(self.cur_str[:2]),''.join(self.cur_str[2:])])\n",
    "           \n",
    "            \n",
    "                \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    # 贪心\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        lst = list(time.replace(\":\", \"\"))\n",
    "        lst.sort()\n",
    "                \n",
    "        min_num = min(lst)\n",
    "\n",
    "        #seconds\n",
    "        for i in lst:\n",
    "            # time为19:35 包括\":\"\n",
    "            if i > time[4]:\n",
    "                return time[:4] + i\n",
    "            \n",
    "        #tens of seconds\n",
    "        for i in lst:\n",
    "            # i不能为6 因为time[4]不可能为0 因为如果time[4]为0 任何time[0-3]都会比time[4]大 会在上一个for loop里得到return结果并return\n",
    "            if i > time[3] and i < \"6\":\n",
    "                return time[:3] + i + min_num\n",
    "        \n",
    "        #hours\n",
    "        for i in lst:\n",
    "            if i > time[1]:\n",
    "                # i不能为4 因为time[3-4]不可能为0 因为如果time[3-4]为0 任何time[0-1]都会比time[3-4]大 会在之前的for loop里得到return结果并return\n",
    "                if time[0] != \"2\" or i < \"4\":\n",
    "                    # min_num必然小于等于2和6 因为任何time[3]必然小于等于6 time[0]必然小于等于2\n",
    "                    return f\"{time[0]}{i}:{min_num}{min_num}\"\n",
    "\n",
    "        #tens of hours            \n",
    "        for i in lst:\n",
    "            if i > time[0] and i <= \"2\":\n",
    "                # min_num最大为2 因为time[0]最大为2\n",
    "                return f\"{i}{min_num}:{min_num}{min_num}\"\n",
    "\n",
    "        # min_num最大为2 因为time[0]最大为2\n",
    "        # 读题 - 下一个距离当前时间最近的时刻 - eg. \"23:59\"\n",
    "        return f\"{min_num}{min_num}:{min_num}{min_num}\"\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        cand = set()\n",
    "        for t1 in time:\n",
    "            for t2 in time:\n",
    "                if t1 != \":\" and t2 != \":\":\n",
    "                    tt = t1+t2\n",
    "                    cand.add(tt)\n",
    "                    \n",
    "        double_digits = sorted(list(cand))\n",
    "        hour, minute = time[:2], time[-2:]\n",
    "        \n",
    "        idx = double_digits.index(minute)\n",
    "        if idx == len(double_digits)-1:\n",
    "            minute = double_digits[0]\n",
    "        else:\n",
    "            if int(double_digits[idx+1]) < 60:\n",
    "                minute = double_digits[idx+1]\n",
    "                return hour + \":\" + minute\n",
    "            else:\n",
    "                minute = double_digits[0]\n",
    "\n",
    "        idx = double_digits.index(hour)\n",
    "        if idx == len(double_digits)-1:\n",
    "            hour = double_digits[0]\n",
    "        else:\n",
    "            if int(double_digits[idx+1]) < 24:\n",
    "                hour = double_digits[idx+1]\n",
    "            else:\n",
    "                hour = double_digits[0]\n",
    "    \n",
    "        return hour + \":\" + minute\n",
    "\n",
    "\n",
    "            \n",
    "            \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        time = time.replace(\":\", \"\")\n",
    "        s = set(list(time))\n",
    "        \n",
    "        flag = False\n",
    "        for h in range(24):\n",
    "            for m in range(60):\n",
    "                t = \"{:0>2}{:0>2}\".format(h, m)\n",
    "                if t == time:\n",
    "                    flag = True\n",
    "                else:\n",
    "                    if flag:\n",
    "                        if set(list(t)) | s == s: return \"{:0>2}:{:0>2}\".format(h, m)\n",
    "        \n",
    "        for h in range(24):\n",
    "            for m in range(60):\n",
    "                t = \"{:0>2}{:0>2}\".format(h, m)\n",
    "                if flag:\n",
    "                    if set(list(t)) | s == s: return \"{:0>2}:{:0>2}\".format(h, m)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "    \t# time_new = list(map(int,time[:2]+time[3:]))\n",
    "        time_new = list(map(int,time[:2]+time[3:]))\n",
    "        se = set()\n",
    "        # se = set()\n",
    "        for i in range(4):\n",
    "            se.add(time_new[i])\n",
    "        if time_new[3]!=max(se):\n",
    "            for i in range(10):\n",
    "                if time_new[3]+1+i in se:\n",
    "                    return time[:4]+str(time_new[3]+1+i)\n",
    "\n",
    "        if time_new[2]!=max(se):\n",
    "            for i in range(6):\n",
    "                if time_new[2]+1+i <6 and time_new[2]+1+i in se:\n",
    "                    return time[:3]+str(time_new[2]+1+i)+str(min(se)) \n",
    "        if time_new[1]!=max(se):\n",
    "            for i in range(10):\n",
    "                if (time_new[0]!=2 and time_new[1]+1+i in se) or (time_new[0]==2 and time_new[1]+1+i<4 and time_new[1]+1+i in se):\n",
    "                    return time[0]+str(time_new[1]+1+i)+':'+str(min(se))+str(min(se))  \n",
    "\t\t\n",
    "        for i in range(2):\n",
    "            if (time_new[0]+1+i<3 and time_new[0]+1+i in se):\n",
    "                return str(time_new[0]+1+i)+str(min(se)) +':'+str(min(se))+str(min(se)) \n",
    "        return str(min(se))+str(min(se)) +':'+str(min(se))+str(min(se))                     "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        choices = set()\n",
    "        for i in time:\n",
    "            if i != ':':\n",
    "                choices.add(int(i))\n",
    "        choice_list = list(choices)\n",
    "        choice_list.sort()\n",
    "        # 第4位\n",
    "        time4 = int(time[4])\n",
    "        for i in choice_list:\n",
    "            if i > time4:\n",
    "                time = time[0:4] + str(i)\n",
    "                return time\n",
    "        # 第3位\n",
    "        time3 = int(time[3])\n",
    "        for i in choice_list:\n",
    "            if time3 < i < 6:\n",
    "                time = time[0:3] + str(i) + time[4]\n",
    "                # 第4位取最小值\n",
    "                time = time[0:4] + str(choice_list[0])\n",
    "                return time\n",
    "\n",
    "        # 第2位\n",
    "        time2 = int(time[1])\n",
    "        time1 = int(time[0])\n",
    "        if time1 in [0, 1]:\n",
    "            max_v = 9\n",
    "        else:\n",
    "            max_v = 3\n",
    "        for i in choice_list:\n",
    "            if time2 < i <= max_v:\n",
    "                time = time[0:1] + str(i) + time[2:5]\n",
    "                # 后两位取最小值\n",
    "                time = time[0:3] + str(choice_list[0]) + str(choice_list[0])\n",
    "                return time\n",
    "\n",
    "        # 第1位\n",
    "        time1 = int(time[0])\n",
    "        for i in choice_list:\n",
    "            if time1 < i <= 2:\n",
    "                time = str(i) + time[1:5]\n",
    "                # 后三位取最小值\n",
    "                time = time[0] + str(choice_list[0]) + \":\" + str(choice_list[0]) + str(choice_list[0])\n",
    "                return time\n",
    "        return str(choice_list[0]) + str(choice_list[0]) + \":\" + str(choice_list[0]) + str(choice_list[0])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        time = time[:2] + time[3:]\n",
    "        nums = sorted(list(set(time)))\n",
    "        for n1 in nums:\n",
    "            for n2 in nums:\n",
    "                for n3 in nums:\n",
    "                    for n4 in nums:\n",
    "                        candi = n1+n2+n3+n4\n",
    "                        if candi < '2400' and n3 < '6' and candi > time:\n",
    "                            return n1+n2+':'+n3+n4\n",
    "        c = nums[0] if nums[0] != 0 else nums[1]\n",
    "        return c*2+':'+c*2\n",
    "        \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        nums, hour, minute = set(time), int(time[:2]), int(time[3:])\n",
    "        m = hour * 60 + minute\n",
    "        while True:\n",
    "            m += 1\n",
    "            hour = m // 60 % 24\n",
    "            minute = m % 60\n",
    "            if hour < 10: \n",
    "                hour = '0' + str(hour)\n",
    "            else:\n",
    "                hour = str(hour)\n",
    "            if minute < 10: \n",
    "                minute = '0' + str(minute)\n",
    "            else:\n",
    "                minute = str(minute)\n",
    "            for i, ch in enumerate(hour + minute):\n",
    "                if ch not in nums:\n",
    "                    break\n",
    "                if i == 3:\n",
    "                    return hour + ':' + minute\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        # 23:59\n",
    "        if time == '00:00' or time == \"11:11\" or time == \"22:22\":\n",
    "            return time\n",
    "        cur_hour, cur_min = map(int, time.split(':'))\n",
    "        def check(cur):\n",
    "            for c in cur:\n",
    "                if c not in time:\n",
    "                    return False\n",
    "            return True\n",
    "        # print(cur_hour, cur_min)\n",
    "        for pace in range(1, 24 * 60):\n",
    "            minute = cur_min + pace\n",
    "            hour = (minute // 60 + cur_hour) % 24\n",
    "            minute = minute % 60\n",
    "            part1 = str(hour) if hour > 9 else '0' + str(hour)\n",
    "            part2 = str(minute) if minute > 9 else '0' + str(minute)\n",
    "            tmp = part1 + ':' + part2\n",
    "            if check(tmp):\n",
    "                return tmp\n",
    "        return None\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        cand = set()\n",
    "        for t1 in time:\n",
    "            for t2 in time:\n",
    "                if t1 != \":\" and t2 != \":\":\n",
    "                    tt = t1+t2\n",
    "                    cand.add(tt)\n",
    "                    \n",
    "        double_digits = sorted(list(cand))\n",
    "        hour, minute = time[:2], time[-2:]\n",
    "        \n",
    "        idx = double_digits.index(minute)\n",
    "        if idx == len(double_digits)-1:\n",
    "            minute = double_digits[0]\n",
    "        else:\n",
    "            if int(double_digits[idx+1]) < 60:\n",
    "                minute = double_digits[idx+1]\n",
    "                return hour + \":\" + minute\n",
    "            else:\n",
    "                minute = double_digits[0]\n",
    "\n",
    "        idx = double_digits.index(hour)\n",
    "        if idx == len(double_digits)-1:\n",
    "            hour = double_digits[0]\n",
    "        else:\n",
    "            if int(double_digits[idx+1]) < 24:\n",
    "                hour = double_digits[idx+1]\n",
    "            else:\n",
    "                hour = double_digits[0]\n",
    "    \n",
    "        return hour + \":\" + minute\n",
    "\n",
    "\n",
    "            \n",
    "            \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        choices = set()\n",
    "        for i in time:\n",
    "            if i != ':':\n",
    "                choices.add(int(i))\n",
    "        choice_list = list(choices)\n",
    "        choice_list.sort()\n",
    "        # 第4位\n",
    "        time4 = int(time[4])\n",
    "        for i in choice_list:\n",
    "            if i > time4:\n",
    "                time = time[0:4] + str(i)\n",
    "                return time\n",
    "        # 第3位\n",
    "        time3 = int(time[3])\n",
    "        for i in choice_list:\n",
    "            if time3 < i < 6:\n",
    "                time = time[0:3] + str(i) + time[4]\n",
    "                # 第4位取最小值\n",
    "                time = time[0:4] + str(choice_list[0])\n",
    "                return time\n",
    "\n",
    "        # 第2位\n",
    "        time2 = int(time[1])\n",
    "        time1 = int(time[0])\n",
    "        if time1 in [0, 1]:\n",
    "            max_v = 9\n",
    "        else:\n",
    "            max_v = 3\n",
    "        for i in choice_list:\n",
    "            if time2 < i <= max_v:\n",
    "                time = time[0:1] + str(i) + time[2:5]\n",
    "                # 后两位取最小值\n",
    "                time = time[0:3] + str(choice_list[0]) + str(choice_list[0])\n",
    "                return time\n",
    "\n",
    "        # 第1位\n",
    "        time1 = int(time[0])\n",
    "        for i in choice_list:\n",
    "            if time1 < i <= 2:\n",
    "                time = str(i) + time[1:5]\n",
    "                # 后三位取最小值\n",
    "                time = time[0] + str(choice_list[0]) + \":\" + str(choice_list[0]) + str(choice_list[0])\n",
    "                return time\n",
    "        return str(choice_list[0]) + str(choice_list[0]) + \":\" + str(choice_list[0]) + str(choice_list[0])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        def valid(x):\n",
    "            hour, minute = int(x[:2]), int(x[3:])\n",
    "            return hour <= 23 and minute < 60\n",
    "\n",
    "        def time_between(x, y):\n",
    "            hour, minute = int(x[:2]), int(x[3:])\n",
    "            h, m = int(y[:2]), int(y[3:])\n",
    "            pre, aft = 60 * hour + minute, h * 60 + m \n",
    "            if aft > pre:\n",
    "                return aft - pre \n",
    "            else:\n",
    "                return 24 * 60 - pre + aft \n",
    "        \n",
    "        ans = []\n",
    "        seen = set()\n",
    "        for i in time:\n",
    "            if i != ':':\n",
    "                seen.add(i)\n",
    "        for i in seen:\n",
    "            for j in seen:\n",
    "                for k in seen:\n",
    "                    for l in seen:\n",
    "                        tmp = i + j + ':' + k + l \n",
    "                        if valid(tmp):\n",
    "                            ans.append([tmp, time_between(time, tmp)])\n",
    "        ans.sort(key=lambda p: p[1])\n",
    "        return ans[0][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        def valid(x):\n",
    "            hour, minute = int(x[:2]), int(x[3:])\n",
    "            return hour <= 23 and minute < 60\n",
    "\n",
    "        def time_between(x, y):\n",
    "            hour, minute = int(x[:2]), int(x[3:])\n",
    "            h, m = int(y[:2]), int(y[3:])\n",
    "            pre, aft = 60 * hour + minute, h * 60 + m \n",
    "            if aft > pre:\n",
    "                return aft - pre \n",
    "            else:\n",
    "                return 24 * 60 - pre + aft \n",
    "        \n",
    "        ans = []\n",
    "        seen = set(time) - set(':')\n",
    "        for i in seen:\n",
    "            for j in seen:\n",
    "                for k in seen:\n",
    "                    for l in seen:\n",
    "                        tmp = i + j + ':' + k + l \n",
    "                        if valid(tmp):\n",
    "                            ans.append([tmp, time_between(time, tmp)])\n",
    "        ans.sort(key=lambda p: p[1])\n",
    "        return ans[0][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def nextClosestTime(self, time: str) -> str:\n",
    "        time_str = time[:2] + time[3:]\n",
    "        chars = list(set(time_str))\n",
    "        chars.sort(reverse=True)\n",
    "        num_chars = len(chars)\n",
    "        chars_order = {char:i for i,char in enumerate(chars)}\n",
    "\n",
    "        changed = False\n",
    "        reverse = time_str[::-1]\n",
    "        for i, char in enumerate(reverse):\n",
    "            if i == 0:\n",
    "                if chars_order[char] != 0:\n",
    "                    new_char = chars[chars_order[char] - 1]\n",
    "                    reverse = new_char + reverse[(i+1):]\n",
    "                    changed = True\n",
    "            if i == 1:\n",
    "                if chars_order[char] != 0:\n",
    "                    candidates = list(chars[:chars_order[char]])\n",
    "                    for new_char in candidates[::-1]:\n",
    "                        if int(new_char) in range(1, 6):\n",
    "                            if changed:\n",
    "                                new_minute = new_char + chars[-1]\n",
    "                                if new_minute < reverse[:2][::-1]:\n",
    "                                    reverse = chars[-1] + new_char + reverse[(i+1):]\n",
    "                                    break\n",
    "                            else:\n",
    "                                reverse = chars[-1] + new_char + reverse[(i+1):]\n",
    "                                changed = True\n",
    "                                break\n",
    "                if changed:\n",
    "                    break\n",
    "            if i == 2:\n",
    "                max_2 = '3' if reverse[-1] == '2' else '9'\n",
    "                if chars_order[char] != 0:\n",
    "                    candidates = list(chars[:chars_order[char]])\n",
    "                    for new_char in candidates[::-1]:\n",
    "                        if int(new_char) in range(1, int(max_2) + 1):\n",
    "                            reverse = chars[-1]+chars[-1] + new_char + reverse[-1]\n",
    "                            changed = True\n",
    "                            break\n",
    "            if i == 3:\n",
    "                max_1 = '2'\n",
    "                if chars_order[char] != 0:\n",
    "                    candidates = list(chars[:chars_order[char]])\n",
    "                    for new_char in candidates[::-1]:\n",
    "                        if int(new_char) in range(1, int(max_1) + 1):\n",
    "                            if changed:\n",
    "                                new_hour = new_char + chars[-1]\n",
    "                                if new_hour < reverse[:2][::-1]:\n",
    "                                    reverse = chars[-1]+chars[-1]+chars[-1] + new_char\n",
    "                                    changed = True\n",
    "                            else:\n",
    "                                reverse = chars[-1]+chars[-1]+chars[-1] + new_char\n",
    "                                changed = True\n",
    "        if changed:\n",
    "            reverse_back = reverse[::-1]\n",
    "            return reverse_back[:2] + ':' + reverse_back[2:]\n",
    "        \n",
    "        if '0' in chars:\n",
    "            return '00:00'\n",
    "        elif '1' in chars:\n",
    "            return '11:11'\n",
    "        elif '2' in chars:\n",
    "            return '22:22'\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
